//
//  MyOrderViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/1/9.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "MyOrderViewController.h"
#import "OrderViewCell.h"
#import "MyOrderModel.h"
#import "UIImageView+WebCache.h"
#import "OrderDeatailViewController.h"
#import "IAPHelper.h"
#import "IAPProduct.h"
@import StoreKit;

@interface MyOrderViewController ()<UITableViewDelegate, UITableViewDataSource,OrderViewCellDelegate>{
    int j;
    UIView *bgView;
    UIView *payView;
    IAPProduct *product;
    NSInteger mark;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *arrOrder;
@property (nonatomic, strong) IAPHelper  *m_iapHelper;
@property (nonatomic, strong) NSMutableArray *m_productArray;

@end

@implementation MyOrderViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    j = 1;
    [self requestListDataStrNum:@"1" isRefrsh:YES];
    [self notifyRequestListData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.arrOrder = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    [self.tableView.superview insertSubview:[UIView new] atIndex:0];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyRefrehData) name:@"MyOrderRefresh" object:nil];
}

- (void)notifyRefrehData {
    [self requestListDataStrNum:@"1" isRefrsh:YES];
    [self removePayView];
}

- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT-64) style:UITableViewStylePlain];
        _tableView.estimatedRowHeight =70;
        _tableView.estimatedSectionHeaderHeight =0;
        _tableView.estimatedSectionFooterHeight =0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.arrOrder count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.arrOrder.count > 0) {
        if ([[self.arrOrder[indexPath.row] ZFJG] isEqualToString:@"0"]) {
            if ([[self.arrOrder[indexPath.row] KC_PRICE] isEqualToString:@"0"]) {
                return 180;
            }
            return 225;
        } else {
            return 180;
        }
    }
    return 225;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"discoverCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil) {
        OrderViewCell *orderViewCell = [[[NSBundle mainBundle] loadNibNamed:@"OrderViewCell" owner:self options:nil] lastObject];
        orderViewCell.delegate = self;
        orderViewCell.btnPay.tag = indexPath.row;
        if (self.arrOrder.count > 0 && self.arrOrder != nil) {
            orderViewCell.lbOrderNum.text = [self.arrOrder[indexPath.row] KC_NAME];

            if ([[self.arrOrder[indexPath.row] ZFJG] isEqualToString:@"0"]) {
                if ([[self.arrOrder[indexPath.row] KC_PRICE] isEqualToString:@"0"]) {
                    [orderViewCell.lbState setTextColor:WRGBColor(54, 157, 46)];
                    orderViewCell.lbState.text = @"已支付";
                    orderViewCell.btnPay.hidden = YES;
                    orderViewCell.lineView.hidden = YES;
                } else {
                    [orderViewCell.lbState setTextColor:[UIColor redColor]];
                    orderViewCell.lbState.text = @"未支付";
                    orderViewCell.btnPay.hidden = NO;
                    orderViewCell.lineView.hidden = NO;
                }
            } else {
                [orderViewCell.lbState setTextColor:WRGBColor(54, 157, 46)];
                orderViewCell.lbState.text = @"已支付";
                orderViewCell.btnPay.hidden = YES;
                orderViewCell.lineView.hidden = YES;
            }
            orderViewCell.lbOrderNum.text = [self.arrOrder[indexPath.row] ORDERNO];
            [orderViewCell.imgCell sd_setImageWithURL:[NSURL URLWithString:[self.arrOrder[indexPath.row] PICURL]] placeholderImage:[UIImage imageNamed:@"school_image.png"]];
            orderViewCell.lbTitle.text = [self.arrOrder[indexPath.row] KC_NAME];
            orderViewCell.lbMoney.text = [NSString stringWithFormat:@"￥%@",[self.arrOrder[indexPath.row] KC_PRICE]];
            orderViewCell.lbPriceNum.text = [NSString stringWithFormat:@"共1件商品 ￥%@",[self.arrOrder[indexPath.row] KC_PRICE]];

        }
        cell = orderViewCell;
    }

    return cell;
}

- (void)noWifiRefershingEnd {
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;
}

- (void)notifyRequestListData{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noWifiRefershingEnd) name:REFRESHINGEND object:nil];

    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [self requestListDataStrNum:@"1" isRefrsh:YES];
        j = 1;
    }];

    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrNum:num isRefrsh:NO];
    }];
}

- (void)requestListDataStrNum:(NSString *)pageNum isRefrsh:(BOOL)isRefrsh{

    [WShareUtil sharedData].isShowWait = NO;

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        parametersDict = @{@"content": @{@"dto": @{@"page":pageNum,@"limit": @"10",@"mode":@"hxjt"},@"revert": @"list",@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"apptype":@"ios"},@"mode": @"native",@"service":@"order"};
    } else {
         parametersDict = @{@"content": @{@"dto": @{@"page":pageNum,@"limit": @"10",@"mode":@"hxjt"},@"revert": @"list",@"username":@"",@"apptype":@"ios"},@"mode": @"native",@"service":@"order"};
    }
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        if ([successStr isEqualToString:@"false"]) {
            return;
        }
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if (isRefrsh) {
            [self.arrOrder removeAllObjects];
        }

        NSArray *arrData = returnDic[@"data"];

        for (NSDictionary *dic in arrData) {
            MyOrderModel *myOrderModel = [MyOrderModel mj_objectWithKeyValues:dic];
            [self.arrOrder addObject:myOrderModel];
            WLog(@"%@",myOrderModel);
        }
        [self.tableView reloadData];
        [self noWifiRefershingEnd];

        ///* --- 图片式提醒
        UIView *view = [self.tableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (arrData.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.tableView addSubview:_nonePage];
        }
        if (arrData.count < 10) {
//      拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.tableView.footer endRefreshingWithNoMoreData];
        }

    } failure:^(NSError *error) {
        [self noWifiRefershingEnd];
        WLog(@"失败");
    } showProgress:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if([SKPaymentQueue canMakePayments])
    {
        OrderDeatailViewController *bugVc = [[OrderDeatailViewController alloc] init];
        bugVc.title = @"订单明细";
        bugVc.myOrderModel = self.arrOrder[indexPath.row];
        [self.navigationController pushViewController:bugVc animated:YES];
    }
    else
    {
        UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"您的手机没有打开程序内付费购买"
                                                           delegate:nil cancelButtonTitle:NSLocalizedString(@"关闭",nil) otherButtonTitles:nil];

        [alerView show];
    }
}

- (void)delegatBtnClick:(UIButton *)button {
//    [self reportMyOrderSubmitInvoiceInfo:button.tag];
    [self createPayView:button.tag];
}


// 我的订单中提交订单
- (void)reportMyOrderSubmitInvoiceInfo:(NSInteger)tag {
    NSDictionary *dtoDic;
    NSDictionary *parametersDict;
    NSString *username;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }

        NSString *strId;
        if (![WShareUtil strNilOrEmpty:[self.arrOrder[tag] ID]]){
            strId = [self.arrOrder[tag] ID];
        } else {
            strId = @"";
        }

        NSString *orderNo;
        if (![WShareUtil strNilOrEmpty:[self.arrOrder[tag] ORDERNO]]){
            orderNo = [self.arrOrder[tag] ORDERNO];
        } else {
            orderNo = @"";
        }
        [WShareUtil sharedData].orderId = strId;
        dtoDic = @{@"cat":@"0",@"orderId":strId,@"orderNo":orderNo};
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"revert":@"payorder",@"username":username,@"apptype":@"ios",@"dto":dtoDic}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [WShareUtil sharedData].dicOrder = returnDic;
            [self createPayView:tag];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)createPayView:(NSInteger)tag {

    mark = tag;
    bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgView.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
    [self.view addSubview:bgView];

    payView = [[UIView alloc] initWithFrame:CGRectMake(0, WSCREENH_HEIGHT - 180, WSCREENH_WIDTH, 180)];
    payView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:payView];

    UILabel *lbTit = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 80) * 0.5, 5, 80, 44)];
    lbTit.text = @"付款";
    lbTit.textAlignment = NSTextAlignmentCenter;
    [lbTit setTextColor:[UIColor blackColor]];

    //分割线
    UILabel *lbLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, WSCREENH_WIDTH, 1)];
    lbLine.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    
    UIButton *btnClose = [[UIButton alloc] initWithFrame:CGRectMake(WSCREENH_WIDTH - 30, 18, 15, 15)];
    [btnClose setImage:[UIImage imageNamed:@"GB.png"] forState:UIControlStateNormal];
    [btnClose addTarget:self action:@selector(removePayView) forControlEvents:UIControlEventTouchUpInside];

    UILabel *lbPay = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 50) * 0.5 - 25, 60, 50, 44)];
    lbPay.text = @"支付";
    lbPay.textAlignment = NSTextAlignmentCenter;
    [lbPay setTextColor:[UIColor blackColor]];

    UILabel *lbMoney = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 50) * 0.5 + 25, 60, 50, 44)];

    lbMoney.text = [NSString stringWithFormat:@"￥%@",[self.arrOrder[tag] KC_PRICE]];

    lbMoney.textAlignment = NSTextAlignmentCenter;
    [lbMoney setTextColor:[UIColor colorWithRed:0.95 green:0.44 blue:0.23 alpha:1]];

    UIButton *btnPay = [[UIButton alloc] initWithFrame:CGRectMake(20, 110, WSCREENH_WIDTH - 40, 45)];
    btnPay.layer.masksToBounds = YES;
    btnPay.layer.cornerRadius = 5;
    btnPay.backgroundColor = [UIColor colorWithRed:0.95 green:0.29 blue:0 alpha:1];
    [btnPay setTitle:@"确认支付" forState:UIControlStateNormal];
    [btnPay setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [btnPay addTarget:self action:@selector(btnPayClick) forControlEvents:UIControlEventTouchUpInside];

    [payView addSubview:lbTit];
    [payView addSubview:lbLine];
    [payView addSubview:btnClose];
    [payView addSubview:lbPay];
    [payView addSubview:lbMoney];
    [payView addSubview:btnPay];
}

- (void)btnPayClick {

    NSString *strCourseId = [self.arrOrder[mark] KC_ID];

    [self requestBuyCourse:strCourseId];

    [WShareUtil sharedData].isMember = NO;

    [WShareUtil sharedData].isShowWait = YES;
    [WShareUtil showWait:YES frame:CGRectMake(0, 32, WSCREENH_WIDTH, WSCREENH_HEIGHT)];
}

- (void)requestBuyCourse:(NSString *)strCourseId {

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"hxjt",@"productId":strCourseId},@"revert":@"remaining",@"username":username},@"mode":@"native",@"service":@"order"};
    }else {
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"hxjt",@"productId":strCourseId},@"revert":@"remaining",@"nologinuser":nologinuser},@"mode":@"native",@"service":@"order"};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
      
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {

            if (![WShareUtil sharedData].isWDDD) {

                [WShareUtil sharedData].dicBuySymbol = @{@"boughten":@"1",@"chosen":@"0",@"id":strCourseId};
            }
            [WShareUtil showAlert:@"温馨提示" message:@"购买成功"];

            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }

        [WShareUtil sharedData].isWDDD = NO;

        [WShareUtil showWait:NO frame:CGRectZero];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)removePayView {
    [payView removeFromSuperview];
    [bgView removeFromSuperview];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removePayView];
}


@end
